package cz.muni.fi.pa165.rentalofconstructionmachinery.dao.impl;

import cz.muni.fi.pa165.rentalofconstructionmachinery.dao.CustomerDAO;
import cz.muni.fi.pa165.rentalofconstructionmachinery.entity.Customer;
import java.util.List;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import org.springframework.stereotype.Repository;

/**
 *
 * @author stefan.rakonjac
 */
@Repository(value = "customerDao")
public class CustomerDAOImpl implements CustomerDAO {
    
    @PersistenceContext
    private EntityManager entityManager;

    @Override
    public void createCustomer(Customer customer) {
        if (null == customer) {
            throw new IllegalArgumentException("Customer 'customer' must not be null.");
        }
     
        entityManager.persist(customer);
    }

    @Override
    public void deleteCustomer(Customer customer) {
        if (null == customer) {
            throw new IllegalArgumentException("Customer 'customer' must not be null.");
        }
        
        entityManager.remove(entityManager.merge(customer));
    }

    @Override
    public void updateCustomer(Customer customer) {
        if (null == customer) {
            throw new IllegalArgumentException("Customer 'customer' must not be null.");
        }
        
        entityManager.merge(customer);
    }

    @Override
    public List<Customer> getAllCustomers() {
        List<Customer> customers = entityManager.createQuery("SELECT c FROM Customer c", Customer.class).getResultList();
        return customers;
    }

    @Override
    public Customer getCustomerById(Long id) {
        if (null == id) {
            throw new IllegalArgumentException("Long 'id' must not be null.");
        }
        
        Customer customer = entityManager.createQuery("SELECT c FROM Customer c WHERE c.id=" + id, Customer.class).getSingleResult();
        return customer;
    }
}
